﻿using mozhi.smarterp.BasicData.Organizations.Repository;
using mozhi.smarterp.BasicData.Organizations.Service;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;

namespace mozhi.smarterp.BasicData.Organizations
{
    public class OrganizationAppService : BasicDataAppService, IOrganizationAppService
    {
        private IOrganizationRepository _repository;
        private IGuidGenerator _guidGenerator;
        private OrganizationManager _manager;

        public OrganizationAppService(IOrganizationRepository repository , IGuidGenerator guidGenerator , OrganizationManager manager)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
            _manager = manager;
        }

        public async Task<OrganizationDto> CreateAsync(OrganzationCreateDto input)
        {
            var count = await _repository.CountAsync();

            if (count > 0)
                throw new UserFriendlyException("组织信息已存在", "100000");

            var organization = new Organization(_guidGenerator.Create() , input.OfficialName , input.OfficialName , input.TaxIDNumber , input.AccountingStandard , input.ActivatedDate , input.StandardCurrencyId);

            await _repository.InsertAsync(organization);

            return ObjectMapper.Map<Organization, OrganizationDto>(organization);
        }

        public async Task<OrganizationDto> GetAsync()
        {
            var organization = await _repository.FirstOrDefaultAsync();

            return ObjectMapper.Map<Organization, OrganizationDto>(organization);
        }

        public async Task<OrganizationDto> UpdateAsync(OrganzationUpdateDto input)
        {
            var organization = await _manager.ChangeAsync(input.Id ,input.OfficialName, 
                input.TaxIDNumber, input.StandardCurrencyId, input.AccountingStandard, input.ActivatedDate);
            await _repository.UpdateAsync(organization);

            return ObjectMapper.Map<Organization, OrganizationDto>(organization);
        }
    }
}
